package pers.wwz.study.springbootparams.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/cookie")
public class CookieController {



    /**
     * 访问/cookie 可以获得一个counter的cookie值，且每访问一次则自增一次，这是一个简单的访问计数器功能。
     * @param counter
     * @param response
     * @return
     */
    @GetMapping("/cookie")
    @ResponseBody
    public String getCookie(@CookieValue(value = "counter", defaultValue = "0") int counter,HttpServletResponse response) {
        log.info("counter:{}", counter);
        counter += 1;
        String newValue = counter + "";
        // 设置Cookie
        response.addCookie(new Cookie("counter", newValue));
        return newValue;
    }


    /**
     * 获取全部参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/allCookies")
    public ResponseEntity<Map<String, String>>allCookies(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> valueMap = new HashMap<String, String>();
        for (Cookie cookie : request.getCookies()) {
            valueMap.put(cookie.getName(), cookie.getValue());
            log.info("cookie[{}]={}", cookie.getName(), cookie.getValue());
        }
        // 设置Cookie
        response.addCookie(new Cookie("key", UUID.randomUUID().toString()));
        return new ResponseEntity<Map<String, String>>(valueMap, HttpStatus.OK);
    }

    /**
     * 清理全部Cookie
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/clearCookies")
    public ResponseEntity<Map<String, String>> clearCookies(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> valueMap = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if(cookies !=null){
            for (Cookie cookie : request.getCookies()) {
                valueMap.put(cookie.getName(), cookie.getValue());
                log.info("cookie[{}]={}", cookie.getName(), cookie.getValue());
                // 清除
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

        return new ResponseEntity<Map<String, String>>(valueMap, HttpStatus.OK);
    }









}
